package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;

import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    private RestHighLevelClient client;

    /**
     * 分页过滤
     * @param requestParams
     * @return
     * @throws IOException
     */

    @Override
    public PageResult getPage(RequestParams requestParams) throws IOException {

        //创建request请求
        SearchRequest request = new SearchRequest("hotel");
        //采用布尔查询
        buildBoolQuery(requestParams,  request);
        if (requestParams.getLocation()!=null) {
            request.source().sort(SortBuilders
                    .geoDistanceSort("location", new GeoPoint(requestParams.getLocation()))
                    .order(SortOrder.ASC)
                    .unit(DistanceUnit.KILOMETERS)
            );
        }
        //对请求分页
        int page = requestParams.getPage();
        int size = requestParams.getSize();
        request.source().from((page-1) * size)
                .size(requestParams.getSize());
        //发送请求
        SearchResponse response = client.search(request,RequestOptions.DEFAULT);
        return handleResponse(response);

    }
    private void buildBoolQuery(RequestParams requestParams,  SearchRequest request) {
        String key= requestParams.getKey();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //关键字
        if (key==null||"".equals(key)){
            boolQuery.must(QueryBuilders.matchAllQuery());

        }else {
           boolQuery.must(QueryBuilders.matchQuery("all",key));
            //request.source().query(QueryBuilders.matchQuery("all",key));
        }
        //对请求过滤
        //城市
        if (StringUtils.isNotBlank(requestParams.getCity())){
            boolQuery.filter(QueryBuilders.termQuery("city",requestParams.getCity()));
        }
        //品牌
        if (StringUtils.isNotBlank(requestParams.getBrand())){
            boolQuery.filter(QueryBuilders.termQuery("brand",requestParams.getBrand()));
        }
        //星级
        if  (StringUtils.isNotBlank(requestParams.getStarName())){
            boolQuery.filter(QueryBuilders.termQuery("starName",requestParams.getStarName()));
        }
        //价格
        if (requestParams.getMinPrice()!=null&&requestParams.getMaxPrice()!=null){
            boolQuery.filter(QueryBuilders.rangeQuery("price")
                    .gte(requestParams.getMinPrice()).lte(requestParams.getMaxPrice()));
        }
        //算分控制
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(boolQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                //过滤条件
                new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("isAD", true),
                        //算分函数
                        ScoreFunctionBuilders.weightFactorFunction(10))
        });
        request.source().query(functionScoreQuery);

    }

    private PageResult handleResponse(SearchResponse response) {
        SearchHits hits = response.getHits();
        Integer totalNum = (int)hits.getTotalHits().value;
       // System.out.println("查询到的总条数为" + totalNum);
        ArrayList<HotelDoc> list = new ArrayList<>();
        //所有源数据
        SearchHit[] hitsAraary = hits.getHits();
        for (SearchHit hit : hitsAraary) {
            //每个索引对象JSON形式
            String json = hit.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);

            Map<String, HighlightField> highlightMap = hit.getHighlightFields();
            if (highlightMap != null && highlightMap.size() > 0) {
                HighlightField highlightFieldName = highlightMap.get("name");
                Text[] highlightFieldNames = highlightFieldName.fragments();
                if (highlightFieldNames != null) {
                    String name = StringUtils.join(highlightFieldNames);
                    hotelDoc.setName(name);
                }
            }
            Object[] sortValues = hit.getSortValues();
            if (sortValues!=null&&sortValues.length>0){
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }
            list.add(hotelDoc);

        }
        return new PageResult(totalNum,list);
    }

}
